﻿using System;
using System.Windows;
using GBAExtentionLib;
using Microsoft.Phone.Controls;

namespace GBAEmulator
{

    public class GBAWatcherService
    {
        private static PhoneApplicationFrame _frame;

        private const string FileExtention = "gba";

        private static DirectoryWatcher _watcher;

        private static Action<FileSelectorEvent> FileSelectedAction { get; set; }

        public static bool IsOpen { get { return _watcher != null && _watcher.Visibility == Visibility.Visible; } }

        public static void Start(DirectoryWatcher watcher, Action<FileSelectorEvent> action)
        {
            if (_watcher != null) _watcher.Visibility = Visibility.Collapsed;
            _watcher = watcher;
            _watcher.FileExtention = FileExtention;
            _watcher.FileSelected += WatcherFileSelected;
            FileSelectedAction = action;
            _frame = Application.Current.RootVisual as PhoneApplicationFrame;
            if (_frame != null)
            {
                _frame.BackKeyPress += GBAWatcherServiceBackKeyPress;
            }
            _watcher.Visibility = Visibility.Visible;
        }

        static void Stop()
        {
            if (_frame != null)
                _frame.BackKeyPress -= GBAWatcherServiceBackKeyPress;
            if (_watcher != null)
                _watcher.Visibility = Visibility.Collapsed;
            _watcher = null;
            FileSelectedAction = null;
        }

        static void WatcherFileSelected(object sender, FileSelectorEvent e)
        {
            if (FileSelectedAction != null)
                FileSelectedAction.Invoke(e);
            Stop();
        }

        static void GBAWatcherServiceBackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (IsOpen)
            {
                e.Cancel = true;
                WatcherFileSelected(_watcher, null);
            }
        }
    }

}
